let currentPage = 1;
let pageSize = 10;
let totalPages = 1;
let totalCount = 0;
let allScores = [];
let filteredScores = [];
let currentEditingScoreId = null;
let classOptions = [];
let courseOptions = [];
let studentOptions = [];
let userRole = null; // 用户角色

function validateScore(score) {
    const errors = [];

    if (score !== null && score !== undefined && score !== '') {
        const numScore = parseFloat(score);
        if (isNaN(numScore)) {
            errors.push('成绩必须是有效数字');
        } else if (numScore < 0 || numScore > 100) {
            errors.push('成绩必须在0-100之间');
        }
    }

    return errors;
}

function validateStudentId(studentId) {
    const errors = [];

    if (!studentId || studentId === '') {
        errors.push('请选择学生');
    }

    return errors;
}

function validateCourseId(courseId) {
    const errors = [];

    if (!courseId || courseId === '') {
        errors.push('请选择课程');
    }

    return errors;
}

function checkScoreExists(studentId, courseId, excludeId = null) {
    return allScores.some(score =>
        score.student_id === parseInt(studentId) &&
        score.course_id === parseInt(courseId) &&
        score.id !== excludeId
    );
}

document.addEventListener('DOMContentLoaded', function() {
    initializePage();
});

async function initializePage() {
    await getUserRole();
    loadClassOptions();
    loadCourseOptions();
    if (userRole !== '0') {
        loadStudentOptions();
    }
    loadScores();
    bindEvents();
}

// 获取用户角色
async function getUserRole() {
    try {
        const response = await fetch('/api/user/info');
        const result = await response.json();

        if (result.success) {
            userRole = result.data.role;
        } else {
            console.error('获取用户信息失败:', result.msg);
            userRole = null;
        }
    } catch (error) {
        console.error('获取用户信息出错:', error);
        userRole = null;
    }
}

function bindEvents() {
    document.getElementById('searchInput').addEventListener('input', debounce(filterScores, 300));
    document.getElementById('classFilter').addEventListener('change', filterScores);
    document.getElementById('courseFilter').addEventListener('change', filterScores);
    document.getElementById('addScoreForm').addEventListener('submit', handleAddScore);
    document.getElementById('editScoreForm').addEventListener('submit', handleEditScore);
    document.getElementById('confirmDeleteBtn').addEventListener('click', handleDeleteScore);
    document.getElementById('addScoreModal').addEventListener('hidden.bs.modal', resetAddForm);
    document.getElementById('editScoreModal').addEventListener('hidden.bs.modal', resetEditForm);
}

async function loadClassOptions() {
    try {
        const response = await fetch('/api/classes/options');
        const result = await response.json();

        if (result.success) {
            classOptions = result.data;
            populateClassFilter();
        } else {
            console.error('加载班级选项失败:', result.msg, result.error);
            showError('加载班级选项失败：' + result.msg);
        }
    } catch (error) {
        console.error('加载班级选项出错:', error);
        showError('加载班级选项失败：网络错误');
    }
}

async function loadCourseOptions() {
    try {
        const response = await fetch('/api/courses/options');
        const result = await response.json();

        if (result.success) {
            courseOptions = result.data;
            populateCourseSelects();
            populateCourseFilter();
        } else {
            console.error('加载课程选项失败:', result.msg, result.error);
            showError('加载课程选项失败：' + result.msg);
        }
    } catch (error) {
        console.error('加载课程选项出错:', error);
        showError('加载课程选项失败：网络错误');
    }
}

async function loadStudentOptions() {
    try {
        const response = await fetch('/api/students/options');
        const result = await response.json();

        if (result.success) {
            studentOptions = result.data;
            populateStudentSelects();
        } else {
            console.error('加载学生选项失败:', result.msg, result.error);
            showError('加载学生选项失败：' + result.msg);
        }
    } catch (error) {
        console.error('加载学生选项出错:', error);
        showError('加载学生选项失败：网络错误');
    }
}

function populateClassFilter() {
    const filterSelect = document.getElementById('classFilter');
    
    filterSelect.innerHTML = `
    '<option value="">${userRole == '0' ? '当前' : '所有'}班级</option>'
    `;
    
    classOptions.forEach(classItem => {
        const option = document.createElement('option');
        option.value = classItem.id;
        option.textContent = classItem.display;
        filterSelect.appendChild(option);
    });
}

function populateCourseFilter() {
    const filterSelect = document.getElementById('courseFilter');
    
    filterSelect.innerHTML = '<option value="">所有课程</option>';
    
    courseOptions.forEach(course => {
        const option = document.createElement('option');
        option.value = course.id;
        option.textContent = course.display;
        filterSelect.appendChild(option);
    });
}

function populateCourseSelects() {
    const addSelect = document.getElementById('addScoreCourse');
    const editSelect = document.getElementById('editScoreCourse');
    
    addSelect.innerHTML = '<option value="">请选择课程</option>';
    editSelect.innerHTML = '<option value="">请选择课程</option>';
    
    courseOptions.forEach(course => {
        const option = document.createElement('option');
        option.value = course.id;
        option.textContent = course.display;
        
        addSelect.appendChild(option.cloneNode(true));
        editSelect.appendChild(option);
    });
}

function populateStudentSelects() {
    const addSelect = document.getElementById('addScoreStudent');
    const editSelect = document.getElementById('editScoreStudent');
    
    addSelect.innerHTML = '<option value="">请选择学生</option>';
    editSelect.innerHTML = '<option value="">请选择学生</option>';
    
    studentOptions.forEach(student => {
        const option = document.createElement('option');
        option.value = student.id;
        option.textContent = student.display;
        
        addSelect.appendChild(option.cloneNode(true));
        editSelect.appendChild(option);
    });
}

async function loadScores() {
    showLoading();

    try {
        const params = new URLSearchParams({
            page: currentPage,
            page_size: pageSize
        });

        const searchTerm = document.getElementById('searchInput').value.trim();
        if (searchTerm) {
            params.append('search', searchTerm);
        }

        const classFilter = document.getElementById('classFilter').value;
        if (classFilter) {
            params.append('class_id', classFilter);
        }

        const courseFilter = document.getElementById('courseFilter').value;
        if (courseFilter) {
            params.append('course_id', courseFilter);
        }

        const response = await fetch(`/api/scores?${params}`);
        const result = await response.json();

        if (result.success) {
            const data = result.data;
            allScores = data.items;
            filteredScores = [...allScores];

            totalPages = data.pagination.total_pages;
            currentPage = data.pagination.current_page;
            totalCount = data.pagination.total_count;

            displayScores();
        } else {
            console.error('加载成绩数据失败:', result.msg, result.error);
            showError('加载失败：' + result.msg + (result.error ? ' - ' + result.error : ''));
            showEmptyState();
        }
    } catch (error) {
        console.error('加载成绩数据出错:', error);
        showError('加载失败：网络错误');
        displayScores();
    }
}

function showLoading() {
    document.getElementById('loadingSpinner').style.display = 'block';
    document.getElementById('scoreTableContainer').style.display = 'none';
    document.getElementById('emptyState').style.display = 'none';
}

function showEmptyState() {
    document.getElementById('loadingSpinner').style.display = 'none';
    document.getElementById('scoreTableContainer').style.display = 'none';
    document.getElementById('emptyState').style.display = 'block';
    updateScoreCount(0);
}

function displayScores() {
    document.getElementById('loadingSpinner').style.display = 'none';

    if (filteredScores.length === 0) {
        showEmptyState();
        return;
    }

    document.getElementById('scoreTableContainer').style.display = 'block';
    document.getElementById('emptyState').style.display = 'none';

    renderScoreTable(filteredScores);
    renderPagination();
    updateScoreCount(totalCount);
}

function renderScoreTable(scores) {
    const tbody = document.getElementById('scoreTableBody');
    tbody.innerHTML = '';

    scores.forEach(score => {
        const row = document.createElement('tr');
        row.className = 'fade-in';

        let actionColumn = '';
        if (userRole !== '0') {
            actionColumn = `
                <td>
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-outline-primary btn-sm"
                                onclick="editScore(${score.id})" title="编辑">
                            <i class="fas fa-edit"></i>
                            编辑
                        </button>
                        <button type="button" class="btn btn-outline-danger btn-sm"
                                onclick="deleteScore(${score.id}, '${score.student_name} - ${score.course_name}')" title="删除">
                            <i class="fas fa-trash"></i>
                            删除
                        </button>
                    </div>
                </td>
            `;
        }

        row.innerHTML = `
            <td><strong>${score.sno}</strong></td>
            <td>${score.student_name}</td>
            <td><span class="badge bg-info">${score.class_display}</span></td>
            <td><span class="badge bg-secondary">${score.course_name}</span></td>
            <td>${score.score !== null ? '<span class="badge bg-success">' + score.score + '</span>' : '<span class="text-muted">未录入</span>'}</td>
            <td>${score.exam_date ? formatDate(score.exam_date) : '<span class="text-muted">未设置</span>'}</td>
            <td>${score.remark ? '<small class="text-muted">' + score.remark + '</small>' : '<span class="text-muted">无</span>'}</td>
            <td>${formatDateTime(score.created_time)}</td>
            ${actionColumn}
        `;
        tbody.appendChild(row);
    });
}

function renderPagination() {
    const pagination = document.getElementById('pagination');
    pagination.innerHTML = '';

    if (totalPages <= 1) return;

    const prevLi = document.createElement('li');
    prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
    prevLi.innerHTML = `
        <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">
            <i class="fas fa-chevron-left"></i>
            上一页
        </a>
    `;
    pagination.appendChild(prevLi);

    for (let i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            const li = document.createElement('li');
            li.className = `page-item ${i === currentPage ? 'active' : ''}`;
            li.innerHTML = `<a class="page-link" href="#" onclick="changePage(${i})">${i}</a>`;
            pagination.appendChild(li);
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            const li = document.createElement('li');
            li.className = 'page-item disabled';
            li.innerHTML = '<span class="page-link">...</span>';
            pagination.appendChild(li);
        }
    }

    const nextLi = document.createElement('li');
    nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
    nextLi.innerHTML = `
        <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">
            <i class="fas fa-chevron-right"></i>
            下一页
        </a>
    `;
    pagination.appendChild(nextLi);
}

function updateScoreCount(count) {
    document.getElementById('listCount').textContent = count;
}

function changePage(page) {
    if (page < 1 || page > totalPages || page === currentPage) return;
    currentPage = page;
    loadScores();
}

function filterScores() {
    currentPage = 1;
    loadScores();
}

function resetFilters() {
    document.getElementById('searchInput').value = '';
    document.getElementById('classFilter').value = '';
    document.getElementById('courseFilter').value = '';
    currentPage = 1;
    loadScores();
}

async function handleAddScore(event) {
    event.preventDefault();

    const form = event.target;
    const formData = new FormData(form);

    const scoreData = {
        student_id: parseInt(formData.get('student_id')),
        course_id: parseInt(formData.get('course_id')),
        score: formData.get('score') ? parseFloat(formData.get('score')) : null,
        exam_date: formData.get('exam_date') || null,
        remark: formData.get('remark') || null
    };

    // 验证数据
    const errors = [];
    errors.push(...validateStudentId(scoreData.student_id));
    errors.push(...validateCourseId(scoreData.course_id));
    errors.push(...validateScore(scoreData.score));

    if (checkScoreExists(scoreData.student_id, scoreData.course_id)) {
        errors.push('该学生该课程的成绩已存在');
    }

    if (errors.length > 0) {
        showError('数据验证失败：\n' + errors.join('\n'));
        return;
    }

    try {
        const response = await fetch('/api/scores', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(scoreData)
        });

        const result = await response.json();

        if (result.success) {
            showSuccess('成绩添加成功！');
            bootstrap.Modal.getInstance(document.getElementById('addScoreModal')).hide();
            loadScores();
        } else {
            showError('添加失败：' + result.msg + (result.error ? ' - ' + result.error : ''));
        }
    } catch (error) {
        console.error('添加成绩出错:', error);
        showError('添加失败：网络错误');
    }
}

function editScore(scoreId) {
    const score = allScores.find(s => s.id === scoreId);
    if (!score) {
        showError('找不到要编辑的成绩记录');
        return;
    }

    currentEditingScoreId = scoreId;

    document.getElementById('editScoreId').value = score.id;
    document.getElementById('editScoreStudent').value = score.student_id;
    document.getElementById('editScoreCourse').value = score.course_id;
    document.getElementById('editScoreValue').value = score.score || '';
    document.getElementById('editScoreExamDate').value = score.exam_date || '';
    document.getElementById('editScoreRemark').value = score.remark || '';

    const modal = new bootstrap.Modal(document.getElementById('editScoreModal'));
    modal.show();
}

async function handleEditScore(event) {
    event.preventDefault();

    const form = event.target;
    const formData = new FormData(form);

    const scoreData = {
        student_id: parseInt(formData.get('student_id')),
        course_id: parseInt(formData.get('course_id')),
        score: formData.get('score') ? parseFloat(formData.get('score')) : null,
        exam_date: formData.get('exam_date') || null,
        remark: formData.get('remark') || null
    };

    // 验证数据
    const errors = [];
    errors.push(...validateStudentId(scoreData.student_id));
    errors.push(...validateCourseId(scoreData.course_id));
    errors.push(...validateScore(scoreData.score));

    if (checkScoreExists(scoreData.student_id, scoreData.course_id, currentEditingScoreId)) {
        errors.push('该学生该课程的成绩已存在');
    }

    if (errors.length > 0) {
        showError('数据验证失败：\n' + errors.join('\n'));
        return;
    }

    try {
        const response = await fetch(`/api/scores/${currentEditingScoreId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(scoreData)
        });

        const result = await response.json();

        if (result.success) {
            showSuccess('成绩更新成功！');
            bootstrap.Modal.getInstance(document.getElementById('editScoreModal')).hide();
            loadScores();
        } else {
            showError('更新失败：' + result.msg + (result.error ? ' - ' + result.error : ''));
        }
    } catch (error) {
        console.error('更新成绩出错:', error);
        showError('更新失败：网络错误');
    }
}

function deleteScore(scoreId, scoreInfo) {
    currentEditingScoreId = scoreId;
    document.getElementById('deleteScoreInfo').textContent = scoreInfo;

    const modal = new bootstrap.Modal(document.getElementById('deleteScoreModal'));
    modal.show();
}

async function handleDeleteScore() {
    try {
        const response = await fetch(`/api/scores/${currentEditingScoreId}`, {
            method: 'DELETE'
        });

        const result = await response.json();

        if (result.success) {
            showSuccess(result.msg);
            bootstrap.Modal.getInstance(document.getElementById('deleteScoreModal')).hide();
            loadScores();
        } else {
            showError('删除失败：' + result.msg + (result.error ? ' - ' + result.error : ''));
        }
    } catch (error) {
        console.error('删除成绩出错:', error);
        showError('删除失败：网络错误');
    }
}

function resetAddForm() {
    const form = document.getElementById('addScoreForm');
    form.reset();
    form.classList.remove('was-validated');

    // 清除所有验证状态
    const inputs = form.querySelectorAll('.form-control, .form-select');
    inputs.forEach(input => {
        input.classList.remove('is-invalid', 'is-valid');
    });
}

function resetEditForm() {
    const form = document.getElementById('editScoreForm');
    form.reset();
    form.classList.remove('was-validated');
    currentEditingScoreId = null;

    // 清除所有验证状态
    const inputs = form.querySelectorAll('.form-control, .form-select');
    inputs.forEach(input => {
        input.classList.remove('is-invalid', 'is-valid');
    });
}

// 工具函数
function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}
